<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="elTree"
          :data="departmentList"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            v-permission="'setrole'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >
            添加员工
          </el-button>
          <el-button size="mini" @click="excelImport">excel导入</el-button>
          <el-button size="mini" @click="excelExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column
            align="center"
            prop="staffPhoto"
            label="头像"
            width="100"
          >
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :size="40"
                :src="row.staffPhoto"
              />

              <div v-else class="usernameImg">
                {{ row.username.charAt(2) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="username"
            label="姓名"
            width="120"
          />
          <el-table-column align="center" prop="mobile" label="手机号" sortable />
          <el-table-column
            align="center"
            prop="workNumber"
            label="工号"
            sortable
          />
          <el-table-column
            align="center"
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template v-slot="{ row }">
              <span>{{ row.formOfEmployment === 1 ? "正式" : "非正式" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" />
          <el-table-column
            align="center"
            prop="timeOfEntry"
            label="入职时间"
            sortable
          />
          <el-table-column align="center" prop="" label="操作">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="lookEmployee(row.id)">
                查看
              </el-button>
              <el-button size="mini" type="text" @click="roleFn(row.id)">
                角色
              </el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"
                  style="margin-left: 10px"
                >
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" type="flex" justify="end" align="middle">
          <el-pagination
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          /></el-row>
      </div>
    </div>
    <importExcelVue
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployee"
    />
    <!-- 角色弹层 -->
    <el-dialog title="角色" :visible.sync="dialogVisible">
      <el-checkbox-group v-model="roleNewList">
        <el-checkbox
          v-for="item in roleOldList"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="16">
          <el-button size="mini" @click="dialogVisible = false">
            取 消
          </el-button>
          <el-button size="mini" type="primary" @click="assignRole()">
            确 定
          </el-button>
        </el-col>
      </el-row>
      <!-- <span slot="footer" class="dialog-footer"> </span> -->
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import {
  getEmployeeApi,
  excelExportApi,
  delEmployeeApi,
  getEmployeeRoleApi,
  getEmployeeDetail,
  assignRoleApi
} from '@/api/employee'
import fileSaver from 'file-saver'
import importExcelVue from './components/importExcel.vue'
export default {
  name: 'Employee',
  components: {
    importExcelVue
  },
  data() {
    return {
      departmentList: [], // 左侧树状结构数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 第几页
        pagesize: 10, // 每页多少条
        keyword: ''
      },
      tableData: [], // 右侧表格数据
      total: 0, // 测试总条数
      showExcelDialog: false, // 表格导入组件状态显示隐藏
      dialogVisible: false, // 角色弹层显示隐藏
      roleOldList: [], // 放请求到的角色列表
      roleNewList: [], // 选中的角色列表
      resId: null // 当前列的id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      const newRes = transListToTreeData(res, 0)
      this.departmentList = newRes
      this.queryParams.departmentId = newRes[0].id
      this.$nextTick(() => {
        this.$refs.elTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployee()
    },
    // 点击左侧树状图
    selectNode(val) {
      this.queryParams.departmentId = val.id
      this.queryParams.page = 1
      this.getEmployee()
    },
    async getEmployee() {
      const { total, rows } = await getEmployeeApi(this.queryParams)
      this.total = total
      this.tableData = rows
    },
    // 换页
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getEmployee()
    },
    // 输入值改变的时候触发
    changeValue() {
      // 单位时间内只执行最后一次
      // this 的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清除上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployee()
      }, 1000)
    },
    // 表格导出
    async excelExport() {
      const res = await excelExportApi()
      console.log(res)
      fileSaver.saveAs(res, '员工表.xlsx')
    },
    // 表格导入
    excelImport() {
      this.showExcelDialog = true
    },
    // 删除角色
    async delEmployee(i) {
      console.log(this.tableData.length)
      await delEmployeeApi(i)
      // 虽然后端删除了，但是前端页面还没更新，所以这里数组长度用1判断而不是0
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      // 重新获取新的数据
      this.getEmployee()
      this.$message.success('删除成功')
    },
    // 查看员工
    lookEmployee(id) {
      // path 路径跳转 query 传参
      // this.$router.push(`/employee/detail?id=${id}`);
      // 另一种写法
      // path 路径跳转 动态路由传参 params 注意：需要配置动态路由
      this.$router.push(`/employee/detail/${id}`)
    },
    // 点击列表中的角色
    async roleFn(id) {
      this.resId = id

      const res = await getEmployeeRoleApi()
      this.roleOldList = res
      const res2 = await getEmployeeDetail(id)
      this.roleNewList = res2.roleIds
      this.dialogVisible = true // 调整顺序，要不然弹层打开了，勾选有延迟
    },
    // 角色弹层中的确定按钮
    async assignRole() {
      console.log(this.roleNewList)
      await assignRoleApi(this.resId, this.roleNewList)
      this.$message.success('修改完成')
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
  .usernameImg {
    color: #fff;
    background-color: pink;
    border-radius: 20px;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    margin: 3px 0 3px 20px;
  }
}
</style>
